#include "udpparser.h"
#include "errorhandle.h"
#include "utils.h"
#include <QDebug>
#include <QJsonObject>

UDPParser::UDPParser()
{
    initData();
}

UDPParser::~UDPParser()
{
    delete currUdpData;
}

void UDPParser::initData()
{
    qRegisterMetaType<udpInfo>("udpInfo");
    currUdpData = new udpInfo;
}

int UDPParser::parseSinglePackage(QByteArray singleArr){
    if(singleArr.size() != SINGLE_PACK_SIZE)
        return Errorhandle::DRONE_DATA_SIZE_EXCEPTION;
    // Header
    for(int i = 0; i < SEEK_HEADER_SIZE; ++i){
        if(header.at(i) != singleArr.at(i)){
            return Errorhandle::DRONE_DATA_PARSER_EXCEPTION;
        }
    }
    currUdpData = (udpInfo*) singleArr.data();
    qDebug()<< "Parser: " << *currUdpData;
    return 0;
}

//int UDPParser::parseSinglePackage(QByteArray singleArr)
//{
//    bool ok;
//    initData();

//    if(singleArr.size() != SINGLE_PACK_SIZE)
//        return Errorhandle::DRONE_DATA_SIZE_EXCEPTION;
//    // Header
//    for(int i = 0; i < SEEK_HEADER_SIZE; ++i){
//        if(header.at(i) != singleArr.at(i)){
//            return Errorhandle::DRONE_DATA_PARSER_EXCEPTION;
//        }
//    }
//    QByteArray dataCount = getSegment(singleArr, SEEK_HEADER_SIZE, SEEK_DATA_COL_SIZE);
//    singleList->append(Utils::byteArrayToInt(dataCount, Utils::LittileEndian));
//    qDebug() << "Data count: " << singleList[0];

//    int parseDataRes = parseSingleData(getSegment(singleArr, SEEK_DATA_COUNT_SIZE, SEEK_DATA_SIZE));
//    return parseDataRes;
//}


void UDPParser::readFile()
{
    QFile file(":/UDPOutput.DUPdata");
    bool isReadable = file.open(QIODevice::ReadOnly); //只读模式打开
    if(isReadable == true){
        QByteArray array =  file.readAll();
        QByteArray subArr;
        qDebug() << sizeof(udpInfo) << "PACKAGE SIZE: " << (int)(array.size()/SINGLE_PACK_SIZE);
        for (int i = 0; i < (int)(array.size()/SINGLE_PACK_SIZE); ++i){
            qDebug() << "Index: " << i;
            subArr.clear();
            for (int j = 0; j < SINGLE_PACK_SIZE; ++j){
                subArr.append(array.at((i*SINGLE_PACK_SIZE) + j));
            }
            parseSinglePackage(subArr);
        }
    }
    file.close();
}

QByteArray getSegment(QByteArray buff, int begin, int end)
{
    QByteArray res;
    for(int i = begin; i < end; ++i){
        res.append(buff.at(i));
    }
    return res;
}
